package
{
	import org.flixel.*;
	
	/**
	 * ...
	 * @author JAC
	 */
	public class Player extends Unit
	{
		public static const INVULNERBLE:uint = 0;
		public static const GHOSTLY:uint = 1;
		
		public static var player:Player;
		
		private static var _spawnPoint:FlxPoint;
		
		public function Player(i:int = 0, j:int = 0)
		{
			super(i, j);
			
			player = this;
			
			_spawnPoint = new FlxPoint(i, j);
			
			toggleLight();
			_light.scale.make(3, 3);
			
			init();
		}
		
		override public function destroy():void
		{
			super.destroy();
		}
		
		override public function update():void
		{
			super.update();
			
			// Hack to fix spawning bug
			if (state == INVULNERBLE && !solid)
			{
				solid = true;
			}
			
			if (!alive && state != INVULNERBLE)
			{
				return;
			}
			
			Controller.update();
		}
		
		override public function kill():void
		{
			alive = false;
			play("DYING");
			stopMoving();
			//FlxG.play(Assets.SndFail, Registry.soundVolume);
		}
		
		override public function offsetSpeed(offset:Number = 0, moveForward:Boolean = false):void
		{
			Controller.advance();
			super.offsetSpeed(offset, alive);
		}
		
		public static function spawnAt(i:int = 0, j:int = 0):void
		{
			Registry.player.clear();
			Registry.player.add(new Player(i, j));
		}
		
		public static function get isAlive():Boolean
		{
			return player == null ? false : player.alive;
		}
		
		public static function get midpoint():FlxPoint
		{
			return player.getMidpoint();
		}
		
		override protected function onDeath():void
		{
			if (Tracker.lives == 0)
			{
				super.onDeath();
			}
			else
			{
				Tracker.lives--;
				init(true);
			}
		}
		
		private function init(respawn:Boolean = false):void
		{
			alive = true;
			
			Controller.init();
			StatusEffect.reset();
			Transformer.ghostly(this);
			
			_speed = 150;

			translateToTileByIndex(_spawnPoint.x, _spawnPoint.y);
			
			if (respawn)
			{
				_timer.reset(3000);
				_timer.callback = initCallback;
				flicker(3);
				alive = false;
				state = INVULNERBLE;
				solid = false;
			}
		}
		
		private function initCallback():void
		{
			alive = true;
			state = GHOSTLY;
		}
	}
 }